from aip import AipSpeech
import pyaudio
import wave
import os

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 16000
RECORD_SECONDS = 2
WAVE_OUTPUT_WAV_FILENAME = "read_file.wav"
WAVE_OUTPUT_PCM_FILENAME = "read_file.pcm"

APP_ID = '16054657'
API_KEY = 'iOqUrnNN5Nzwjx3mfQxHcUzE'
SECRET_KEY = 'aIvKvYyTGD792ArHDAK7NObbQcuUhNMq'

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
client.setConnectionTimeoutInMillis(60000)
client.setSocketTimeoutInMillis(60000)


def convert_text_wav(text):
    # 文字转化成 wav
    tmp_read_file = "tmp_read.wav"
    # 调用百度SDK，将文本转化为语音
    result = client.synthesis(text, 'zh', 1, {
        'spd': 4,
        'vol': 14,
        'per': 3
    })
    if not isinstance(result, dict):
        with open(tmp_read_file, 'wb') as f:
            f.write(result)
    return tmp_read_file


def play(file_name):
    # 播放 音频
    os.system("ffplay -autoexit %s" % (file_name))


def play_text(text):
    # 将文字转成音频并播放
    pcm_file = convert_text_wav(text)
    play(pcm_file)


# play_text("你好百度")


def read_file():
    # 开始录音
    audio = pyaudio.PyAudio()
    stream = audio.open(format=FORMAT, channels=CHANNELS,
                        rate=RATE, input=True, frames_per_buffer=CHUNK)
    play_text("请开始说话：")
    frames = []
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
    play_text("录音时间到！")
    stream.stop_stream()
    stream.close()
    audio.terminate()
    # 结束录音
    # 开始写入文件
    out = wave.open(WAVE_OUTPUT_WAV_FILENAME, "wb")
    out.setnchannels(CHANNELS)
    out.setsampwidth(audio.get_sample_size(FORMAT))
    out.setframerate(RATE)
    out.writeframes(b''.join(frames))
    out.close()
    # 写入文件完成


# read_file()
def convert_wav_text():
    # 获取语音文件
    read_file()
    # 转化语音文件为pcm
    os.system("ffmpeg -y -i %s -acodec pcm_s16le -f s16le -ac 1 -ar 16000 %s" %
              (WAVE_OUTPUT_WAV_FILENAME, WAVE_OUTPUT_PCM_FILENAME))
    # 解析pcm
    with open(WAVE_OUTPUT_PCM_FILENAME, 'rb') as fp:
        # 调用百度SDK，将语音转化为文本
        ret = client.asr(fp.read(), 'pcm', 16000, {
            'dev_pid': 1536
        })
        print(ret)


convert_wav_text()
